# -*- coding: utf-8 -*-


import re
from io import BytesIO
import qrcode
from pyzbar.pyzbar import decode as qrdecode
from PIL import Image
import io
import base64

from commons.storage import get_storage


# 若img.save()报错 cannot write mode RGBA as JPEG
# 则img = Image.open(image_path).convert('RGB')
def image_to_base64(image_path):
    img = Image.open(image_path)
    output_buffer = BytesIO()
    img.save(output_buffer, format='JPEG')
    byte_data = output_buffer.getvalue()
    base64_str = base64.b64encode(byte_data)
    return base64_str


def base64_to_image(base64_str, image_path=None):
    base64_data = re.sub('^data:image/.+;base64,', '', base64_str)
    byte_data = base64.b64decode(base64_data)
    image_data = BytesIO(byte_data)
    img = Image.open(image_data)
    if image_path:
        img.save(image_path)
    return img


# 将链接转为二维码输出
def get_matrix_img_by_param(content, img_type='png', box_size=5, border=1, img_name='default'):
    box_size = int(box_size)
    box_size = 50 if box_size > 50 else box_size
    q = qrcode.main.QRCode(box_size=box_size, border=border)
    q.add_data(content)
    m = q.make_image()
    buf = io.BytesIO()
    m.save(buf, img_type)
    data = base64.encodebytes(buf.getvalue()).decode()
    src = 'data:image/png;base64,' + str(data)
    return src.replace("\n", "")
    # return Image.open(buf).show()


def decode_byte_qrcode(byte):
    img = base64_to_image(byte)
    result = qrdecode(img)
    for _r in result:
        if _r.type == "QRCODE":
            return result[0].data.decode()


def decode_path_qrcode(path):
    img = Image.open(path)
    result = qrdecode(img)
    for _r in result:
        if _r.type == "QRCODE":
            return result[0].data.decode()


# 将连接转为二维码并储存,返回oss的url
def save_matrix_img_by_param(content, path, img_type='png', box_size=5, border=1, img_name='default'):
    box_size = int(box_size)
    box_size = 50 if box_size > 50 else box_size
    q = qrcode.main.QRCode(box_size=box_size, border=border)
    q.add_data(content)
    m = q.make_image()

    if not path.endswith(f'.{img_type}'):
        image_path = "{0}.{1}".format(path, img_type)
    else:
        image_path = path

    buf = io.BytesIO()
    m.save(buf, img_type)
    qr_buf = buf.getvalue()
    # 使用oss进行上传操作
    config = {"key_id": "AKIDwf8uQfcIgndCTTBcmfHfma7NLLIzPFtH",
              "secret": "B5h38vQdZFCsHTP4EDwPdbKnzuZx5wXr",
              "bucket": "szhss-1313454947",  # 桶名
              "region": "ap-nanjing",
              "host": "cos.ap-nanjing.myqcloud.com"
              }

    oss = get_storage("tencent")(**config)
    print(f'oss is {oss}')

    oss.upload(image_path, qr_buf)
    image_path = oss.download_url(image_path)
    return image_path


# if __name__ == '__main__':
#     content = 'https://www.baidu.com/'
#     path = '百度二维码.png'
#     print(save_matrix_img_by_param(content, path))
